package com.uduemc.biso.node.web.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.extities.center.Host;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.core.utils.RepertorySrcUtil;
import com.uduemc.biso.node.core.utils.SitePathUtil;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.pojo.ResponseWordOffice;
import com.uduemc.biso.node.web.api.service.HostService;
import com.uduemc.biso.node.web.api.service.RepertoryService;
import com.uduemc.biso.node.web.api.service.UploadService;
import com.uduemc.biso.node.web.component.LibreOfficeConverter;
import com.uduemc.biso.node.web.service.LibreOfficeService;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import feign.form.util.CharsetUtil;

@Service
public class LibreOfficeServiceImpl implements LibreOfficeService {

	@Autowired
	private GlobalProperties globalProperties;

	@Autowired
	private RequestHolder requestHolder;

	@Autowired
	private HostService hostServiceImpl;

	@Autowired
	private RepertoryService repertoryServiceImpl;

	@Autowired
	private UploadService uploadServiceImpl;

	@Override
	public ResponseWordOffice wordToHtml(long hostId, long hRepertoryId) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		Host host = hostServiceImpl.getInfoById(hostId);
		HRepertory hRepertory = repertoryServiceImpl.getInfoByid(hRepertoryId);
		return wordToHtml(host, hRepertory);
	}

	@Override
	public ResponseWordOffice wordToHtml(long hRepertoryId) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		Host host = requestHolder.getHost();
		HRepertory hRepertory = repertoryServiceImpl.getInfoByid(hRepertoryId);
		return wordToHtml(host, hRepertory);
	}

	@Override
	public ResponseWordOffice wordToHtml(HRepertory hRepertory) {
		Host host = requestHolder.getHost();
		return wordToHtml(host, hRepertory);
	}

	@Override
	public ResponseWordOffice wordToHtml(Host host, HRepertory hRepertory) {
		Short type = hRepertory.getType();
		if (type == null || type.shortValue() != (short) 1) {
			return null;
		}

		String suffix = hRepertory.getSuffix();
		if (!(suffix.toLowerCase().equals("doc") || suffix.toLowerCase().equals("docx"))) {
			return null;
		}

		// 首先获取到资源数据
		String basePath = globalProperties.getSite().getBasePath();
		// 通过 basePath 以及 code 获取 用户的目录
		String userPathByCode = SitePathUtil.getUserPathByCode(basePath, host.getRandomCode());
		String repertoryPath = userPathByCode + File.separator + hRepertory.getFilepath();

		if (!FileUtil.isFile(repertoryPath)) {
			return null;
		}

		File repertoryFile = FileUtil.file(repertoryPath);

		String name = FileUtil.getName(repertoryFile);

		long size = FileUtil.size(repertoryFile);

		// 临时生成 html 的目录
		String tempPath = globalProperties.getSite().getTempPath();
		String htmlPath = tempPath + File.separator + "LibreOfficeServiceImpl" + File.separator + "html_" + SecureUtil.md5(hRepertory.getId() + name + size)
				+ File.separator + "index.html";

		File parentFile = new File(htmlPath).getParentFile();

		if (FileUtil.isDirectory(parentFile)) {
			FileUtil.del(parentFile);
		}

		FileUtil.mkdir(parentFile);

		LibreOfficeConverter.convertFile(repertoryPath, htmlPath);

		if (!FileUtil.isFile(htmlPath)) {
			return null;
		}

		String readString = FileUtil.readString(htmlPath, CharsetUtil.UTF_8);

		// 提取 body 标签的内容
		String body = null;
		Pattern ptn = Pattern.compile("<body.*?>(.*?)</body>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
		Matcher matcher = ptn.matcher(readString);
		if (matcher.find()) {
			if (matcher.group(1) != null) {
				body = "<div>\n" + matcher.group(1) + "\n</div>";
			}
		}

		body = StrUtil.replace(body, " class=\"cjk\"", "");

		FileUtil.writeString(body, htmlPath, CharsetUtil.UTF_8);

		// body体里面的img标签，通过img标签中的图片去htmlPath目录下找到对应的图片资源，拷贝到用户资源目录下，同时写入资源数据
		// 然后通过资源数据生成img.src地址，替换到img标签中原图片地址，
		ptn = Pattern.compile("src=\"(index_html_\\w+\\.\\w+)\"", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
		matcher = ptn.matcher(body);
		String imgSrc = null;
		String imgPath = null;
		HRepertory imgHRepertory = null;
		String nodeImageSrcByRepertory = null;
		while (matcher.find()) {
			imgPath = null;
			imgHRepertory = null;
			nodeImageSrcByRepertory = null;

			imgSrc = matcher.group(1);

			imgPath = parentFile + File.separator + imgSrc;
			if (StrUtil.isBlank(imgPath) || !FileUtil.isFile(imgPath)) {
				continue;
			}

			try {
				imgHRepertory = uploadServiceImpl.nodeLocalUploadHandler(host, 0L, imgPath);
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (imgHRepertory == null) {
				continue;
			}

			try {
				nodeImageSrcByRepertory = RepertorySrcUtil.getNodeImageSrcByRepertory(imgHRepertory);
			} catch (Exception e) {
				e.printStackTrace();
			}

			if (nodeImageSrcByRepertory == null) {
				continue;
			}

			body = StrUtil.replace(body, imgSrc, nodeImageSrcByRepertory);

		}

		FileUtil.del(parentFile);

		return ResponseWordOffice.makeResponseWordOffice(name, body);
	}

}
